package com.macro.mall.initialize;
import com.alibaba.cloud.commons.io.Charsets;
import com.alibaba.nacos.shaded.com.google.common.io.CharStreams;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.dto.EsIndexDto;
import com.macro.mall.remton.EsServiceRemton;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * es初始化
 */
@Component
public class EsInitialize implements ApplicationRunner{
    @Resource
    private EsServiceRemton esServiceRemton;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        String indexName="logs";
        EsIndexDto esIndexDto = new EsIndexDto();
        esIndexDto.setIndexName(indexName);
        //读取json文件
        InputStream mappings = EsInitialize.class.getClassLoader().getResourceAsStream("mappings.json");
        InputStream settings = EsInitialize.class.getClassLoader().getResourceAsStream("settings.json");
        String mappingsStr= CharStreams.toString(new InputStreamReader(mappings, Charsets.UTF_8));
        String settingsStr= CharStreams.toString(new InputStreamReader(settings, Charsets.UTF_8));
        esIndexDto.setIndexMappings(mappingsStr);
        esIndexDto.setIndexSetting(settingsStr);
        //校验索引名称是否存在
        CommonResult commonResult = esServiceRemton.searchIndexChecker(esIndexDto.getIndexName());
        String data = (String) commonResult.getData();
        //结果为false执行添加
        if (data.equals("false")){
            esServiceRemton.createProductIndex(esIndexDto);
        }


    }
}
